import datetime
import json
import sqlite3
import time
import requests


gift_name = []


def get_list():
    url = 'https://api.live.bilibili.com/xlive/web-room/v1/giftPanel/giftConfig?platform=pc&room_id=2064239'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/80.0.3987.149 Safari/537.36 '
    }
    try:
        print("开始更新礼物列表")
        con = sqlite3.connect("gift_list.db")
        cur = con.cursor()
        cur.execute("CREATE TABLE IF NOT EXISTS gift(g_name TEXT,price INTEGER)")
        cur.execute("SELECT g_name FROM gift")
        for i in cur:
            if str(i[0]) not in gift_name:
                gift_name.append(str(i[0]))
        html = requests.get(url, headers=headers)
        result = html.json()['data']['list']
        for i in result:
            if str(i['name']) not in gift_name:
                if i['price'] == 0:
                    if str(i['name']) == '小心心':
                        price = 50
                    else:
                        price = 1
                else:
                    price = int(i['price'])
                cur.execute("INSERT INTO gift VALUES(?,?)", (str(i['name']), price))
                con.commit()
                gift_name.append(i['name'])
        print("礼物列表更新完成")
        con.commit()
        cur.close()
        con.close()
    except Exception as e:
        print("更新礼物列表失败！\n" + str(e))


def judge(name):
    price = 1
    if name == '舰长':
        price = 198000
    elif name == '提督':
        price = 1998000
    elif name == '总督':
        price = 19998000
    else:
        con = sqlite3.connect("gift_list.db")
        cur = con.cursor()
        cur.execute("SELECT price FROM gift WHERE g_name=?", (str(name),))
        for i in cur:
            price = i[0]
    return price


def count():
    try:
        today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        date = datetime.date.today() + datetime.timedelta(-1)
        # date = '2020-08-14'
        con = sqlite3.connect("gift.db")
        cur = con.cursor()
        con1 = sqlite3.connect("user.db")
        cur1 = con1.cursor()
        u_user = []
        user = []
        uid = []
        cur.execute("SELECT uid, uname FROM gift")
        for i in cur:
            if i[0] not in uid:
                user.append(i)
                uid.append(i[0])
        print(user)
        cur1.execute("SELECT uid FROM user")
        for i in cur1:
            u_user.append(i[0])
        # print(u_user)
        print("信息载入完成，开始同步")
        count = 1
        for i in user:
            print("开始同步第 " + str(count) + " 个用户的数据")
            if i[0] not in u_user:
                user_id = str(i[0])
                user_name = str(i[1])
                print(str(user_id) + ":" + str(user_name))
                cur1.execute("INSERT INTO user values(?,?,?,?,?,?)", (user_id, user_name, 0, today, 0, 0))
                con1.commit()
                cur.execute("SELECT g_count, g_type FROM gift WHERE uid=?", (user_id,))
                for j in cur:
                    # print(j[0])
                    cur1.execute("SELECT exp FROM user WHERE uid=?", (user_id,))
                    for k in cur1:
                        add = 1
                        if j[1] in gift_name:
                            print("检测非辣条礼物")
                            if j[1] in gift_name:
                                add_exp = judge(str(j[1]))
                            else:
                                print("未知礼物！")
                                add_exp = 1
                            add = j[0] * int(add_exp)
                        else:
                            add = j[0]
                        cur1.execute("UPDATE user SET exp=? WHERE uid=?", (k[0] + add, user_id))
                        con1.commit()
                # time.sleep(10)
            else:
                cur.execute("SELECT g_count, g_type FROM gift WHERE uid=? AND r_day=?", (str(i[0]), date))
                for j in cur:
                    # print(j[0])
                    cur1.execute("SELECT exp FROM user WHERE uid=?", (str(i[0]),))
                    for k in cur1:
                        add = 1
                        if j[1] in gift_name:
                            print("检测非辣条礼物")
                            if j[1] in gift_name:
                                add_exp = judge(str(j[1]))
                            else:
                                print("未知礼物！")
                                add_exp = 1
                            add = j[0] * int(add_exp)
                        else:
                            add = j[0]
                        cur1.execute("UPDATE user SET exp=? WHERE uid=?", (k[0] + add, str(i[0])))
                        con1.commit()
            count += 1
        print("所有用户信息同步成功")
    except Exception as e:
        print(e)
        print("同步出现错误！")


gift_name.append("舰长")
gift_name.append("提督")
gift_name.append("总督")
print(gift_name)
while 1:
    try:
        a_time = time.strftime('%H', time.localtime(time.time()))
        m_time = time.strftime('%M', time.localtime(time.time()))
        if int(m_time) == 00 and int(a_time) == 5:
            get_list()
            count()
            time.sleep(600)
        time.sleep(45)
    except Exception as e:
        print(e)
        time.sleep(60)
